package com.kuafood.flutter_kuafood_camera


import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.media.MediaMuxer
import android.opengl.GLSurfaceView
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.kuafood.flutter_kuafood_camera.codec.MediaEncodeManager
import com.kuafood.flutter_kuafood_camera.codec.MediaMuxerChangeListener
import com.kuafood.flutter_kuafood_camera.codec.VideoEncodeRender
import com.kuafood.flutter_kuafood_camera.record.AudioCapture
import com.kuafood.flutter_kuafood_camera.scale.ScaleGesture
import com.kuafood.flutter_kuafood_camera.surface.CameraSurfaceView
import com.kuafood.flutter_kuafood_camera.utils.AlphaAnimationUtils
import com.kuafood.flutter_kuafood_camera.utils.ByteUtils
import com.kuafood.flutter_kuafood_camera.utils.DisplayUtils
import com.kuafood.flutter_kuafood_camera.utils.FileUtils
import com.otaliastudios.cameraview.*
import com.otaliastudios.cameraview.filter.Filters
import com.otaliastudios.cameraview.frame.Frame
import com.otaliastudios.cameraview.frame.FrameProcessor
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*


import com.otaliastudios.cameraview.*
import com.otaliastudios.cameraview.controls.Facing
import com.otaliastudios.cameraview.controls.Mode
import com.otaliastudios.cameraview.controls.Preview

import java.io.File



class KuaFoodCameraView(context: Context, attrs: AttributeSet?, initialParams: Map<String, Any>?) : FrameLayout(context, attrs), View.OnClickListener, OptionView.Callback {

    private var videoFilePath = ""

    private var mediaEncodeManager: MediaEncodeManager? = null

    private val calcDecibel = Handler()
    //手势缩放监听
    private var scaleGestureDetector: ScaleGestureDetector? = null

    //SeekBar是否正在拖动
    private val isSeekBarOnTouch = false

    var ivFocus:android.widget.ImageView? = null

    var videoEncodeRender: VideoEncodeRender? = null
    var audioCapture: AudioCapture? = null




    ////>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private  lateinit var  camera: CameraView;
    private val controlPanel: ViewGroup by lazy { findViewById(R.id.controls) }
    private var captureTime: Long = 0

    private var currentFilter = 0
    private val allFilters = Filters.values()
    private lateinit var _watermark:TextView;

    companion object {
        private val LOG = CameraLogger.create("DemoApp")
        private const val USE_FRAME_PROCESSOR = false
        private const val DECODE_BITMAP = false
    }


    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.layout_camera_main, this, true)
        initView(rootView, context, initialParams);
    }


    private  fun initView(rootView: View, context: Context, params:Map<String, Any>?) {
        camera = rootView.findViewById(R.id.camera)
//        camera.setBackgroundColor(0x23f2e3)

//        //调节屏幕亮度
        DisplayUtils.adjustBrightness(0.6f, FlutterKuafoodCameraPlugin.activityBinding?.activity)


        initCamera()

    }

    private fun initCamera(){
        CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE)
//        camera.setLifecycleOwner(LifeOwner())
        camera.addCameraListener(Listener())


        if (USE_FRAME_PROCESSOR) {
            camera.addFrameProcessor(object : FrameProcessor {
                private var lastTime = System.currentTimeMillis()
                override fun process(frame: Frame) {
                    val newTime = frame.time
                    val delay = newTime - lastTime
                    lastTime = newTime
                    LOG.v("Frame delayMillis:", delay, "FPS:", 1000 / delay)
                    if (DECODE_BITMAP) {
                        if (frame.format == ImageFormat.NV21
                            && frame.dataClass == ByteArray::class.java) {
                            val data = frame.getData<ByteArray>()
                            val yuvImage = YuvImage(data,
                                frame.format,
                                frame.size.width,
                                frame.size.height,
                                null)
                            val jpegStream = ByteArrayOutputStream()
                            yuvImage.compressToJpeg(
                                Rect(0, 0,
                                frame.size.width,
                                frame.size.height), 100, jpegStream)
                            val jpegByteArray = jpegStream.toByteArray()
                            val bitmap = BitmapFactory.decodeByteArray(jpegByteArray,
                                0, jpegByteArray.size)
                            bitmap.toString()
                        }
                    }
                }
            })
        }
        findViewById<View>(R.id.edit).setOnClickListener(this)
        findViewById<View>(R.id.capturePicture).setOnClickListener(this)
        findViewById<View>(R.id.capturePictureSnapshot).setOnClickListener(this)
        findViewById<View>(R.id.captureVideo).setOnClickListener(this)
        findViewById<View>(R.id.captureVideoSnapshot).setOnClickListener(this)
        findViewById<View>(R.id.toggleCamera).setOnClickListener(this)
        findViewById<View>(R.id.changeFilter).setOnClickListener(this)
        val group = controlPanel.getChildAt(0) as ViewGroup
        _watermark = findViewById<TextView>(R.id.watermark)
        val options: List<Option<*>> = listOf(
            // Layout
            Option.Width(), Option.Height(),
            // Engine and preview
            Option.Mode(), Option.Engine(), Option.Preview(),
            // Some controls
            Option.Flash(), Option.WhiteBalance(), Option.Hdr(),
            Option.PictureMetering(), Option.PictureSnapshotMetering(),
            Option.PictureFormat(),
            // Video recording
            Option.PreviewFrameRate(), Option.VideoCodec(), Option.Audio(), Option.AudioCodec(),
            // Gestures
            Option.Pinch(), Option.HorizontalScroll(), Option.VerticalScroll(),
            Option.Tap(), Option.LongTap(),
            // Watermarks
            Option.OverlayInPreview(_watermark),
            Option.OverlayInPictureSnapshot(_watermark),
            Option.OverlayInVideoSnapshot(_watermark),
            // Frame Processing
            Option.FrameProcessingFormat(),
            // Other
            Option.Grid(), Option.GridColor(), Option.UseDeviceOrientation()
        )
        val dividers = listOf(
            // Layout
            false, true,
            // Engine and preview
            false, false, true,
            // Some controls
            false, false, false, false, false, true,
            // Video recording
            false, false, false, true,
            // Gestures
            false, false, false, false, true,
            // Watermarks
            false, false, true,
            // Frame Processing
            true,
            // Other
            false, false, true
        )
        for (i in options.indices) {
            val view = OptionView<Any>( FlutterKuafoodCameraPlugin.activityBinding?.activity!!.applicationContext)
            view.setOption(options[i] as Option<Any>, this)
            view.setHasDivider(dividers[i])
            group.addView(view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        controlPanel.viewTreeObserver.addOnGlobalLayoutListener {
            BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_HIDDEN
        }
//
//        // Animate the watermark just to show we record the animation in video snapshots
        val animator = ValueAnimator.ofFloat(1f, 0.8f)
        animator.duration = 300
        animator.repeatCount = ValueAnimator.INFINITE
        animator.repeatMode = ValueAnimator.REVERSE
        animator.addUpdateListener { animation ->
            val scale = animation.animatedValue as Float
            _watermark.scaleX = scale
            _watermark.scaleY = scale
            _watermark.rotation = _watermark.rotation + 2

            Log.d("sss",scale.toString())

            if (scale < .9){
                _watermark.text = "改变水印"
            }else {
                _watermark.text = "AAA品质";
            }
//
//
//
//        }
//        animator.start()

    }




    }

    override fun onClick(v: View?) {
//        findViewById<View>(R.id.edit).setOnClickListener(this)
//        findViewById<View>(R.id.capturePicture).setOnClickListener(this)
//        findViewById<View>(R.id.capturePictureSnapshot).setOnClickListener(this)
//        findViewById<View>(R.id.captureVideo).setOnClickListener(this)
//        findViewById<View>(R.id.captureVideoSnapshot).setOnClickListener(this)
//        findViewById<View>(R.id.toggleCamera).setOnClickListener(this)
//        findViewById<View>(R.id.changeFilter).setOnClickListener(this)

        camera.open()


        return
        if(v?.id == R.id.capturePicture){
            println("拍照")
            if (camera.mode == Mode.VIDEO) return run {
                message("Can't take HQ pictures while in VIDEO mode.", false)
            }
            if (camera.isTakingPicture) return
            captureTime = System.currentTimeMillis()
            message("Capturing picture...", false)
            camera.takePicture()
        }else if (v?.id == R.id.edit){
            println("编辑")
        }else if (v?.id == R.id.capturePictureSnapshot) {
            println("水印拍照")
        }else if (v?.id == R.id.captureVideo){
            println("captureVideo")
        }else if (v?.id == R.id.captureVideoSnapshot){
            println("captureVideoSnapshot")
        }else if (v?.id == R.id.toggleCamera){
            println("toggleCamera")
        }else if (v?.id == R.id.changeFilter){
            println("changeFilter")
        }

    }

    override fun <T : Any> onValueChanged(option: Option<T>, value: T, name: String): Boolean {
        return  true
    }

    fun capturePicture(view: View){

    }

    private fun message(content: String, important: Boolean) {
        if (important) {
            println(content)

            Toast.makeText(FlutterKuafoodCameraPlugin.activityBinding?.activity, content, Toast.LENGTH_SHORT).show()
        } else {
            println(content)
            Toast.makeText(FlutterKuafoodCameraPlugin.activityBinding?.activity, content, Toast.LENGTH_SHORT).show()
        }
    }

//    private  inner  class LifeOwner: LifecycleOwner(){
////        override fun getLifecycle(): Lifecycle {
////            return
////        }
//
//    }

    private inner class Listener : CameraListener() {
        override fun onCameraOpened(options: CameraOptions) {

        }

        override fun onCameraError(exception: CameraException) {
            super.onCameraError(exception)
            message("Got CameraException #" + exception.reason, true)
        }

        override fun onPictureTaken(result: PictureResult) {

            if (camera.isTakingVideo) {
                message("Captured while taking video. Size=" + result.size, false)
                return
            }

            message("picture size" + result.location.toString(), important = true);

            println(">>>>>>>>>>>>>>>> onPictureTaken")
            super.onPictureTaken(result)



            // This can happen if picture was taken with a gesture.
//            val callbackTime = System.currentTimeMillis()
//            if (captureTime == 0L) captureTime = callbackTime - 300
//            println("onPictureTaken called! Launching activity. Delay:", callbackTime - captureTime)
//            PicturePreviewActivity.pictureResult = result
//            val intent = Intent(this@CameraActivity, PicturePreviewActivity::class.java)
//            intent.putExtra("delay", callbackTime - captureTime)
//            startActivity(intent)
//            captureTime = 0
//            LOG.w("onPictureTaken called! Launched activity.")
        }

        override fun onVideoTaken(result: VideoResult) {
            super.onVideoTaken(result)
//            LOG.w("onVideoTaken called! Launching activity.")
//            VideoPreviewActivity.videoResult = result
//            val intent = Intent(this@CameraActivity, VideoPreviewActivity::class.java)
//            startActivity(intent)
//            LOG.w("onVideoTaken called! Launched activity.")
        }

        override fun onVideoRecordingStart() {
            super.onVideoRecordingStart()
//            LOG.w("onVideoRecordingStart!")
        }

        override fun onVideoRecordingEnd() {
            super.onVideoRecordingEnd()
            message("Video taken. Processing...", false)
//            LOG.w("onVideoRecordingEnd!")
        }

        override fun onExposureCorrectionChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
            super.onExposureCorrectionChanged(newValue, bounds, fingers)
            message("Exposure correction:$newValue", false)
        }

        override fun onZoomChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
            super.onZoomChanged(newValue, bounds, fingers)
            message("Zoom:$newValue", false)
        }
    }




}